<?php
namespace Weiserver\Controller;
use Think\Controller;
class IndexController extends Controller {
	
	/**
	*	初始化方法
	*/
	protected function _initialize(){
		//parent::_initialize();
	}
	
	/**
	*	微信服务器交互服务
	*/
	public function wxserver(){
		
		$tokenkey=I('get.tokenkey');
		
		if($this->wxcheck()){//判断请求是否来自微信服务器
		
			$echostr=I('get.echostr');//获取微信服务器随机字符串
			
			if(!empty($echostr)){//如果微信服务器随机字符串不为空，网址接入验证
				echo $echostr;
				exit;
			}
		}
		
		$postData=file_get_contents('php://input','r');//获取微信服务器POST数据包
		
		if(!empty($postData)){
			
			//将POST数据包转化成对象
			$xmlobj=simplexml_load_string($postData,'SimpleXMLElement',LIBXML_NOCDATA);
			
			$xmljson=json_encode($xmlobj);
			
			$arrxml=json_decode($xmljson,1);
			$arrxml['tokenkey']=$tokenkey;
			$arrxml['msgtype']='server';
			$dejson=json_encode($arrxml);
			
			$FromUserName=$xmlobj->FromUserName;//获取发送方ID
			$ToUserName=$xmlobj->ToUserName;//获取接收方ID
			$MsgType=$xmlobj->MsgType;//获取消息类型
			
			switch($MsgType){//根据消息类型选择回复方式
				case 'event':
					$Event=$xmlobj->Event;
					switch ($Event) {
						case 'subscribe'://用户关注事件
							if(!empty($xmlobj->EventKey)){
								$EventKey=$xmlobj->EventKey;	
							}
							$Msg="欢迎关注";
							break;
						
						case 'SCAN'://用户已关注扫描二维码事件
							$msg="用户已关注";
							break;
						
						case 'CLICK'://自定义菜单
							$EventKey=$xmlobj->EventKey;
							switch ($EventKey) {
								case 'V1001_TODAY_MUSIC':
									$Msg="您点击的是今日歌曲";
									break;
								
								default:
									$Msg="您点击的是其他事件";
									break;
							}
							break;
						
						default:
							
							break;
					}
					break;
				case 'text':
					$Msg=$xmlobj->Content;//获取发送方消息
					break;
				
				case 'image':
					$Msg=$xmlobj->PicUrl;//获取发送方图片url
					break;
					
				case 'voice':
					$Msg=$xmlobj->Format;
					break;
					
				case 'video':
					$Msg=$xmlobj->MsgId;
					break;
					
				case 'shortvideo':
					$Msg=$xmlobj->MsgId;
					break;
					
				case 'location':
					$Msg=$xmlobj->Label;
					break;
					
				case 'link':
					$Msg=$xmlobj->MsgId;
					break;
					
				default:
					$Msg="未知消息，无法处理";
					break;
			}
			
			//定义回复XML字符串
			$reply="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			</xml>";
			if("笑话"==$Msg){
				$handle = fopen ( "http://api.laifudao.com/open/xiaohua.json", "r" );
//				$ch=curl_init();
//				$url="http://api.laifudao.com/open/xiaohua.json";
//				curl_setopt($ch, CURLOPT_URL, $url);
//				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//				$result=curl_exec($ch);
//				curl_close($ch);
				
				$text = "";
				while ( ! feof ( $handle ) ) {
					$text .= fread ( $handle, 100 );
				}
				fclose ( $handle );
				$hisen = json_decode ( $text ); // 解析json
				$i = 0;
				foreach ( $hisen as $obj ) {//一定要obj对象
					//echo "<h4>" . $obj->title . "</h4>";
					
					$Msg=$obj->content;
					$i = $i + 1;
					if ($i == 1) {//控制输出条数，最多20
						break;
					}
				}
				
				
				
				$result=sprintf($reply,$FromUserName,$ToUserName,time(),$Msg);//格式化XML字符串
				echo $result;//输出（微信服务器访问后获取的XML字符串）
				//var_dump(json_encode($arrxml));
			}else{
				$out=$this->socket($dejson);
				echo "success";
				exit;
			}
		}else{
			echo "error";
		}
	}

	public function accessToken(){//获取access_token
		$ch=curl_init();
		$appid="wxc68d67067803a88d";
		$appcecret="69f02bd9a8eeffbd9c606c8a99cd3475";
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appcecret}";
		//$url="https://www.baidu.com";
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$result=curl_exec($ch);
		echo(curl_error($ch));
		curl_close($ch);
		
		$hisen=json_decode ($result); // 解析json
		$access_token=$hisen->access_token;
		echo $result;
		//echo "vDM4l6u2NS_7v21q9WB4GMFLPlgJrIjK-G2QDz9iQJ-kWvxLmJ82g_zQpSUGcD_oNhpbt1WoChi1LAErjiUVgw-xcBqjh1WPNDjjdla2_WQAZCdABASRU";
	}
	
	//添加客服
	public function addkf(){
		$access_token="vYhev_5dQGlIYx7q0JnIUTGbs7QaixO7_zRBW6qCrPESrtLb66SimIi-M5KW65_9ZVnfCvgRED8Wgy57ie9dgY32_SgdVEyg7CX29P4D9BQNYTfAFAVGB";
		$url="https://api.weixin.qq.com/customservice/kfaccount/add?access_token={$access_token}";
		$kfjson='{
			"kf_account" : "asdfg@gh_0d736829ac27",
			"nickname" : "asdfg",
		}';
		$ch=curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_POST, 1);//模拟POST
		curl_setopt($ch, CURLOPT_POSTFIELDS, $kfjson);
		curl_exec($ch);
		echo(curl_error($ch));
	}
	
	public function getmenu(){//获取自定义菜单
		$access_token="vYhev_5dQGlIYx7q0JnIUTGbs7QaixO7_zRBW6qCrPESrtLb66SimIi-M5KW65_9ZVnfCvgRED8Wgy57ie9dgY32_SgdVEyg7CX29P4D9BQNYTfAFAVGB";
		$url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token={$access_token}";
		$ch=curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_exec($ch);
		echo(curl_error($ch));
		curl_close($ch);
	}
	
	public function setmenu(){//设置自定义菜单
		$access_token="3c3L8M6i8iSTS-bKoHodaak3BRO9JqG8Jib_ObHDHoBOKsDLcV4xENcoPA0S1odM_jksUh15JrCrHAwAmSAGDk9_7RGwQdM2bk5Lg_piYUQTDScAGAXHW";
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
		$menujson='{
		     "button":[
		     {	
		          "type":"click",
		          "name":"今日歌曲",
		          "key":"V1001_TODAY_MUSIC"
		      },
		      {
		           "name":"菜单",
		           "sub_button":[
		           {	
		               "type":"view",
		               "name":"百度一下",
		               "url":"https://m.baidu.com/"
		            },
		            {
		               "type":"view",
		               "name":"微官网",
		               "url":"http://zzj5150.imwork.net/index.php/weixin/weinet/index"
		            },
		            {
		               "type":"view",
		               "name":"退出登录",
		               "url":"http://zzj5150.imwork.net/index.php/weixin/login/logout"
		            }]
		       }]
		}';
		$ch=curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);//模拟POST
		curl_setopt($ch, CURLOPT_POSTFIELDS, $menujson);//post数据
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_exec($ch);
		
	}

	/**
	*	向8000端口发送消息
	*/
	public function socket($Msg){
		$port = 8000;
		$ip = "127.0.0.1";
		
		/*
		+-------------------------------
		*    @socket连接整个过程
		+-------------------------------
		*    @socket_create
		*    @socket_connect
		*    @socket_write
		*    @socket_read
		*    @socket_close
		+--------------------------------
		*/
		
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//		if ($socket < 0) {
//			echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
//		}else {
//			echo "OK.\n";
//		}
		
//		echo "试图连接 '$ip' 端口 '$port'...\n";
		$result = socket_connect($socket, $ip, $port);
//		if ($result < 0) {
//			echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
//		}else {
//			echo "连接OK\n";
//		}
//		
		$in = $Msg."\r\n";
		
		if(!socket_write($socket, $in, strlen($in))) {
//			echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
		}else {
//			echo "发送到服务器信息成功！\n";
//			echo "发送的内容为:<font color='red'>$in</font> <br>";
		}
		
		$Msg="";
		while($out = socket_read($socket, 8192)) {
//			echo "接收服务器回传信息成功！\n";
//			echo "接受的内容为:".$out;
			$Msg=$out;
		}
//		
//		echo "关闭SOCKET...\n";
		socket_close($socket);
//		echo "关闭OK\n";
		return "内容".$Msg;
	}
	
	/**
	*	微信服务器验证
	*/
	private function wxcheck(){
		
		$tokenkey=I('get.tokenkey');
		$user=M('user');
		$where=array('tokenkey'=>$tokenkey);
		$result=$user->where($where)->find();
		$token=$result['token'];
		
		$signature=I('get.signature');//获取微信服务器加密签名
		$timestamp=I('get.timestamp');//获取微信服务器时间戳
		$nonce=I('get.nonce');//获取微信服务器随机数
		$tmparr=array($token,$timestamp,$nonce);//定义一个数组，存储三个参数
		sort($tmparr,SORT_STRING);//进行排序
		$tmpstr=implode($tmparr);//将数组转化成字符串
		$tmpstr=sha1($tmpstr);//进行sha1加密算法
		
		if($tmpstr==$signature){//判断请求是否来自微信服务器
			return true;
		}else{
			return false;
		}
	}
}